//
//  UserDetailViewController.m
//  TwitterFon
//
//  Created by kaz on 11/16/08.
//  Copyright 2008 naan studio. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>

#import "ProfileViewController.h"
#import "GuaziAppDelegate.h"
//#import "WebViewController.h"
#import "FriendListViewController.h"
#import "UserTimelineController.h"
//#import "FavoritesViewController.h"
#import "Followee.h"
#import "ColorUtils.h"
#import "TwoButtonsCell.h"
#import "ContactGroupViewController.h"
#import "ABContactsHelper.h"
#import "ButtonCell.h"
#import "UserService.h"
#import "Card.h"
#import "CardDetailViewController.h"
#import "NetworkUtil.h"

//#define USE_FRIENDSHIP_EXISTS_METHOD

enum {
    ROW_FRIENDS,
    ROW_UPDATES,
    ROW_FAVORITES,
    NUM_ROWS,
};

#define kActionSheetBind 101
#define kActionSheetFollow 102
#define kActionSheetRequestCard 103


@interface ProfileViewController(private)
- (void) postTweet;
- (void) postDirectMessage;
- (void) callPhone;
- (void) sendMessage;
- (void) setUserGroup;
- (void) bindToContact;

- (void) updateUserWithABContact:(ABContact*)abContact;

- (void) displaySMSComposerSheet:(NSArray*)recipients body:(NSString*)body;
- (void) send:(NSArray*)recipients body:(NSString*)body;

- (void) showFollowButton:(ButtonCell*)cell;
- (void) friendship:(ButtonCell*)cell;

- (void) friendCards;
@end


@implementation ProfileViewController

@synthesize cards;

#pragma mark - init & destroy

- (id)initWithProfile:(User*)aUser
{
    self = [super initWithStyle:UITableViewStyleGrouped];
    
    user = aUser;
    if ( [GuaziAppDelegate getAppDelegate].user.userId == aUser.userId ) {
        ownInfo = true;
    }
    else {
        //UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemReply target:self action:@selector(postTweet:)]; 
        //self.navigationItem.rightBarButtonItem = button;
    }
    
    userView = [[UserView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
    [userView setUser:user];
    
    self.cards = [NSMutableArray array];
	
    return self;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


- (void)dealloc 
{
    [userView release];
    [twitterClient release];
    [cards release];
    [super dealloc];
}


#pragma mark - 生命周期方法s

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [userView setNeedsDisplay];
    self.navigationItem.title = user.screenName;
    self.tableView.separatorColor = [UIColor colorWithRed:0.9f green:0.9f blue:0.9f alpha:1.0f];
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
	if ( [user.state compare:kUserStateValid]==NSOrderedSame ) {
        if ( !detailLoaded ) {
            if ( [NetworkUtil isbroadbandAvailable] ) {
                twitterClient = [[TwitterClient alloc] initWithTarget:self action:@selector(userDidReceive:obj:)];
                //[twitterClient getUser:user.screenName];
                [twitterClient getUserById:user.userId];
            }
            else {
                self.cards = (NSMutableArray*) [Card cardsForUser:user.userId];
                detailLoaded = YES;
            }
        }
    }
}


- (void)viewDidDisappear:(BOOL)animated 
{
    if (twitterClient) {
        [twitterClient cancel];
        [twitterClient release];
        twitterClient = nil;
    }
}


#pragma mark - tableview datasource delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ( ownInfo ) {
        return 2;
    }
    else {
        return 3;
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 3;
    }
    else if ( section == 1 ) {
		if ( detailLoaded ) {
			return ownInfo ? NUM_ROWS : NUM_ROWS - 1;
		}
		else {
			return 0;
		}
    }
    else if (section == 2) {
        return 1;
    }
    else {
        return 0;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ( indexPath.section == 0 ) {
        return 60;
    }
    else if (indexPath.section == 1) {
        return 35;
    }
    else if ( indexPath.section == 2 ) {
        return 40;
    }
    else {
        return 0;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    
    NSInteger section = indexPath.section;
    if ( section == 0 ) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"ContactDetailButtonCell"];
        if ( !cell ) {
            cell = [[[TwoButtonsCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"ContactDetailButtonCell"] autorelease];
        }
    }
    else if ( section == 1 ) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"ContactDetailCell"];
        if (!cell) {
            cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"ContactDetailCell"] autorelease];
        }
    }
    else if ( section == 2 ) {
        cell = [tableView dequeueReusableCellWithIdentifier:@"followButtonCell"];
        if ( !cell ) {
            cell = [[[ButtonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"followButtonCell"] autorelease];
        }
        
        ButtonCell* followButtonCell = (ButtonCell*)cell;
        
        UIImage *image = [[UIImage imageNamed:@"deleteButton.png"] stretchableImageWithLeftCapWidth:7 topCapHeight:0];
        UIImage *imagePressed = [[UIImage imageNamed:@"deleteButton_pressed.png"] stretchableImageWithLeftCapWidth:7 topCapHeight:0];
        [followButtonCell setImage:image imagePressed:imagePressed];
        [self showFollowButton:followButtonCell];
    }
	
    if ( section == 0) {
        TwoButtonsCell* buttonCell = (TwoButtonsCell*) cell;
        if ( indexPath.row == 0 ) {
            buttonCell.button1.tag = 101;
            buttonCell.button2.tag = 102;
        }
        else if ( indexPath.row == 1 ) {
            buttonCell.button1.tag = 201;
            buttonCell.button2.tag = 202;
        }
        else if ( indexPath.row == 2 ) {
            buttonCell.button1.tag = 301;
            buttonCell.button2.tag = 302;
        }
        buttonCell.delegate = self;
    }
    else if ( section == 1 ) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        switch (indexPath.row) {
            case ROW_FRIENDS:
                cell.textLabel.text = [NSString stringWithFormat:@" %d 好友", user.friendsCount];
                break;
				/*
            case ROW_FOLLOWERS:
                cell.textLabel.text = [NSString stringWithFormat:@" %d 粉丝", user.followersCount];
                break;
			 */
            case ROW_UPDATES:
                cell.textLabel.text = [NSString stringWithFormat:@" %d 动态", user.statusesCount];
                break;
            case ROW_FAVORITES:
                cell.textLabel.text = [NSString stringWithFormat:@" %d 收藏", user.favoritesCount];
                break;
        }
    }
    
    return cell;
}


#pragma mark - tableview delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    if (indexPath.section == 0) {
    }
    if (indexPath.section == 1) {
        if (indexPath.row == ROW_FAVORITES) {
            if (user.favoritesCount != 0) {
				/*
                 FavoritesViewController *c = [[FavoritesViewController alloc] initWithNibName:@"FavoritesView" bundle:nil];
                 [c loadTimeline:user.screenName];
                 //[self.navigationController pushViewController:c animated:true];
				 GuaziAppDelegate* appDelegate = [GuaziAppDelegate getAppDelegate];
				 UINavigationController* nav = [appDelegate.tabBarController.viewControllers objectAtIndex:appDelegate.tabBarController.selectedIndex];
				 [nav pushViewController:c animated:true];
				 */
            }
        }
        else if (indexPath.row == ROW_UPDATES) {
            if (user.statusesCount != 0) {
                UserTimelineController* userTimeline = [[[UserTimelineController alloc] initWithUser:user] autorelease];
				[userTimeline loadUserTimeline:user.userId];
                //[self.navigationController pushViewController:userTimeline animated:true];
				GuaziAppDelegate* appDelegate = [GuaziAppDelegate getAppDelegate];
				UINavigationController* nav = [appDelegate.tabBarController.viewControllers objectAtIndex:appDelegate.tabBarController.selectedIndex];
				[nav pushViewController:userTimeline animated:true];
            }
        }
        else {
			
            int count = (indexPath.row == ROW_FRIENDS) ? user.friendsCount : user.followersCount;
            if (count > 0) {
                //FriendsViewController *friends = [[[FriendsViewController alloc] initWithScreenName:user.screenName isFollowers:(indexPath.row == 1)] autorelease];
                FriendListViewController *friends = [[[FriendListViewController alloc] initWithUser:user isFollowers:(indexPath.row == 1)] autorelease];
                //[self.navigationController pushViewController:friends animated:true];
				GuaziAppDelegate* appDelegate = [GuaziAppDelegate getAppDelegate];
				UINavigationController* nav = [appDelegate.tabBarController.viewControllers objectAtIndex:appDelegate.tabBarController.selectedIndex];
				[nav pushViewController:friends animated:true];
            }
			 
        }
    }
    else if ( indexPath.section == 2 ) {
        ButtonCell* cell = (ButtonCell*) [tableView cellForRowAtIndexPath:indexPath];
        [self friendship:cell];
    }
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:true];
}


- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ( indexPath.section == 0 ) return nil;
    else return indexPath;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return userView;
    }
    else {
        return nil;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 90;
    }
    else {
        return 0;
    }
}


/*
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if ( section == 1 ) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        UIImage *image = [UIImage imageNamed:@"deleteButton.png"];
        UIImage *imagePressed = [UIImage imageNamed:@"deleteButton_pressed.png"];
        
        [button setBackgroundImage:[image stretchableImageWithLeftCapWidth:7 topCapHeight:0] forState:UIControlStateNormal];
        [button setBackgroundImage:[imagePressed stretchableImageWithLeftCapWidth:7 topCapHeight:0] forState:UIControlStateHighlighted];
        button.frame = CGRectMake(10, 10, 250, 40);
        return button;
    }
    else {
        return nil;
    }
}



- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if ( section == 0 ) {
        return 0;
    }
    else if ( section == 1 ) {
        return 60;
    }
}
 */


- (void) showFollowButton:(ButtonCell*)cell
{
    if ( ownInfo ) return;
    
    if ( [user.relation compare:kUserRelationFollowing]==NSOrderedSame || [user.relation compare:kUserRelationBoth]==NSOrderedSame) {
        [cell setTitle:@"删除联系人"];
    }
    else {
        //没有关注
        [cell setTitle:@"恢复联系人"];
    }
}


- (void)userDidReceive:(TwitterClient*)sender obj:(NSObject*)obj
{
    twitterClient = nil;    
    
    if (sender.hasError) {
        [sender alert];
        return;
    }
    
    NSDictionary *dic = nil;
    if ([obj isKindOfClass:[NSDictionary class]]) {
        dic = (NSDictionary*)obj;

        [user updateWithJSonDictionary:dic];
        [userView setUser:user];
        detailLoaded = true;

        NSMutableArray *indexPath = [NSMutableArray arrayWithObjects:
		 [NSIndexPath indexPathForRow:0 inSection:1],
		 [NSIndexPath indexPathForRow:1 inSection:1],
		 //[NSIndexPath indexPathForRow:2 inSection:1],
		 nil];
		
		if (ownInfo) {
			[indexPath addObject:[NSIndexPath indexPathForRow:2 inSection:1]];
		}
		
        [self.tableView beginUpdates];
        [self.tableView insertRowsAtIndexPaths:indexPath withRowAnimation:UITableViewRowAnimationTop];
        [self.tableView endUpdates];
        
        [user updateDB:YES withName:NO withAccount:NO];
        
        self.cards = user.cards;
        [Card setCardsForUser:user.userId cards:user.cards];
    }
}


- (void)friendshipDidCheck:(TwitterClient*)sender obj:(NSObject*)obj   	 	 
{
    twitterClient = nil;
    
    if (sender.hasError) {
        [sender alert];
        return;
    }
    
    NSNumber *flag = (NSNumber*)obj;  	 	 
    user.following = [flag boolValue] ? 1 : 0;
    [Followee updateDB:user];

    [self.tableView beginUpdates];  	 	 
    [self.tableView insertSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationTop];  	 	 
    [self.tableView endUpdates];  	 	 
}
    

- (void)updateFriendship:(BOOL)created
{
    user.following = created;
    [Followee updateDB:user];
    
    CATransition *animation = [CATransition animation];
    [animation setType:kCATransitionFade];
    [animation setDuration:0.25];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    [self.tableView.layer addAnimation:animation forKey:@"friendshipButton"];

    [self.tableView reloadData];
}

- (void)followDidRequest:(TwitterClient*)sender obj:(NSObject*)obj
{
    BOOL created = (sender.request == TWITTER_REQUEST_CREATE_FRIENDSHIP) ? true : false;
    if (sender.hasError && sender.statusCode == 403) {
        [self updateFriendship:created];
    }
    else if ([obj isKindOfClass:[NSDictionary class]]) {
        [self updateFriendship:created];
    }
    else {
        [sender alert];
    }
    twitterClient = nil;
}

- (void)postTweet:(id)sender
{
	GuaziAppDelegate * appDelegate = [GuaziAppDelegate getAppDelegate];
    PostViewController* postView = appDelegate.postView;
    
    if ([self tabBarController].selectedIndex == TAB_MESSAGES) {
        [postView editDirectMessage:user.screenName];
    }
    else {
        [postView reply:user.screenName];
    }
}


#pragma mark - ButtonsCellDelegate

#define kUserOperationPhone 101
#define kUserOperationMessage 102
#define kUserOperationDM 201
#define kUserOperationCard 202
#define kUserOperationGroup 301
#define kUserOperationBindContact 302

- (NSString*) titleForButton:(NSInteger)tag
{
    if ( tag == kUserOperationPhone ) {
        return @"电话";
    }
    else if ( tag == kUserOperationMessage ) {
        return @"短信";
    }
    else if ( tag == kUserOperationDM ) {
        return @"私信";
    }
    else if ( tag == kUserOperationCard ) {
        if ( [cards count] == 0 ) {
            return @" 索要名片";
        }
        else {
            return @"名片";
        }
    }
    else if ( tag == kUserOperationGroup ) {
        return @"分组";
    }
    else if ( tag == kUserOperationBindContact ) {
        return @"绑定";
    }
    else {
        return @":)";
    }
}


- (UIImage*) imageForButton:(NSInteger)tag
{
    if ( tag == kUserOperationPhone ) {
        return [UIImage imageNamed:@"button_phone.png"];
    }
    else if ( tag == kUserOperationMessage ) {
        return [UIImage imageNamed:@"button_email.png"];
    }
    else if ( tag == kUserOperationDM ) {
        //return [UIImage imageNamed:@"button_dm.png"];
        return [UIImage imageNamed:@"button_person.png"];
    }
    else if ( tag == kUserOperationCard ) {
        return [UIImage imageNamed:@"button_bookmark.png"];
    }
    else if ( tag == kUserOperationGroup ) {
        return [UIImage imageNamed:@"button_home.png"];
    }
    else if ( tag == kUserOperationBindContact ) {
        return [UIImage imageNamed:@"button_person.png"];
    }
    else {
        //return [UIImage imageNamed:@"button_rightarrow.png"];
        return [UIImage imageNamed:@"button_person.png"];
    }
}


- (BOOL) enabledForButton:(NSInteger)tag
{
    if ( tag == kUserOperationCard ) {
        if ( [user.state compare:kUserStateValid] == NSOrderedSame ) {
            return YES;
        }
        else {
            return NO;
        }
    }
    else if ( tag == kUserOperationDM ) {
        if ( [user.state compare:kUserStateValid] == NSOrderedSame && [user.relation compare:kUserRelationBoth] == NSOrderedSame ) return YES;
        else return NO;
    }
    else if ( tag == kUserOperationPhone ) {
        if ( user.phone && [user.phone length] > 0 ) return YES;
        else return NO;
    }
    else if ( tag == kUserOperationMessage ) {
        if ( user.phone && [user.phone length] > 0 ) return YES;
        else return NO;
    }
    else if ( tag == kUserOperationGroup ) {
        return YES;
    }
    else if ( tag == kUserOperationBindContact ) {
        return YES;
    }
    else {
        return NO;
    }
}


- (void) didClickButton:(NSInteger)tag withObject:(id)object
{
    if ( tag == kUserOperationCard ) {
        [self friendCards];
    }
    else if ( tag == kUserOperationDM ) {
        [self postDirectMessage];
    }
    else if ( tag == kUserOperationPhone ) {
        [self callPhone];
    }
    else if ( tag == kUserOperationMessage ) {
        [self sendMessage];
    }
    else if ( tag == kUserOperationGroup ) {
        [self setUserGroup];
    }
    else if ( tag == kUserOperationBindContact ) {
        [self bindToContact];
    }
    else {
    }
}


#pragma mark - 联系人相关的操作


//刷新
- (void) refresh
{
}


//名片
- (void) friendCards
{
    if ( [cards count] == 0 ) {
        //索要名片
        UIActionSheet* sheet = [[UIActionSheet alloc] initWithTitle:[NSString stringWithFormat:@"您还没有%@的名片。索要名片后，系统会自动发送一封私信给您的朋友。您的朋友收到私信后将发送名片给您。是否索要名片？", user.remarkName] 
                                                           delegate:self 
                                                  cancelButtonTitle:@"放弃" 
                                             destructiveButtonTitle:@"确定" 
                                                  otherButtonTitles:nil];
        sheet.tag = kActionSheetRequestCard;
        [sheet showInView:[GuaziAppDelegate getAppDelegate].tabBarController.view];
        [sheet release];
    }
    else {
        //名片列表
        Card* card = [cards objectAtIndex:0];
        CardDetailViewController* controller = [[CardDetailViewController alloc] initWithCard:card];
        [self.navigationController pushViewController:controller animated:YES];
        [controller release];
    }
}


- (void) askCard
{
    if ( twitterClient != nil ) return;
    twitterClient = [[TwitterClient alloc] initWithTarget:self action:@selector(didAskCard:obj:)];
    [twitterClient askCard:user.userId];
}


- (void) didAskCard:(id)sender obj:(NSObject*)obj
{
    twitterClient = nil;
    
    TwitterClient* client = (TwitterClient*) sender;
    if ( [client hasError] ) {
        [client alert];
    }
    else {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" 
                                                        message:@"已经向您的朋友发送了索要名片私信！" 
                                                       delegate:nil 
                                              cancelButtonTitle:@"确定" 
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
}


//设置分组
- (void) setUserGroup
{
	ContactGroupViewController* controller = [[ContactGroupViewController alloc] initWithStyle:UITableViewStylePlain user:user];
	[self.navigationController pushViewController:controller animated:YES];
	[controller release];
}


//发私信
- (void)postDirectMessage
{
    GuaziAppDelegate *appDelegate = [GuaziAppDelegate getAppDelegate];
    PostViewController* postView = appDelegate.postView;
	[postView editDirectMessage:user.screenName];
}


//发动态
- (void) postTweet
{
    GuaziAppDelegate *appDelegate = [GuaziAppDelegate getAppDelegate];
    PostViewController* postView = appDelegate.postView;
	[postView reply:user.screenName];
}


//发短信
- (void) sendMessage
{
	NSArray* array = [NSArray arrayWithObject:user.phone];
    [self send:array body:@""];
	//MessagePicker* picker = [[MessagePicker alloc] initWithController:self recienpts:array body:@""];
	//[picker send];
	//[picker release];
}

//打电话
- (void) callPhone
{
	NSString* url = [NSString stringWithFormat:@"tel://%@", user.phone];
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}

//增加联系人
- (void) bindToContact
{
	UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"将好友添加到本机通讯录" 
															 delegate:self
													cancelButtonTitle:@"取消"
											   destructiveButtonTitle:@"绑定到现有联系人" 
													otherButtonTitles:@"创建新联系人",nil];
    actionSheet.tag = kActionSheetBind;
	[actionSheet showInView:[GuaziAppDelegate getAppDelegate].tabBarController.view];
	[actionSheet release];
}


- (void) didBindToAContact
{
    //绑定现有联系人
    ABPeoplePickerNavigationController *ppnc = [[ABPeoplePickerNavigationController alloc] init];
    ppnc.peoplePickerDelegate = self;
    [self presentModalViewController:ppnc animated:YES];
    [ppnc release];
}


- (void) didBindToNewContact
{
    //增加联系人
    // create a new view controller
    ABContact *contact = [ABContact contact];
    contact.firstname = user.screenName;
    
    //email
    NSRange range = [user.name rangeOfString:@"@"];
    if ( range.location != NSNotFound ) {
        NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:user.name, @"_$!<Home>!$_", nil];
        contact.emailDictionaries = [NSArray arrayWithObject:dic];
    }
    
    //phone
    if ( user.phone != nil && [user.phone length]>0 ) {
        NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:user.phone, @"_$!<Mobile>!$_", nil];
        contact.phoneDictionaries = [NSArray arrayWithObject:dic];
    }
    
    //address
    /*
     NSDictionary* dic = [ABContact addressWithStreet:@"" 
     withCity:user.cityName withState:user.provinceName 
     withZip:@"" withCountry:@"China" withCode:@"cn"];
     contact.addressDictionaries = [NSArray arrayWithObject:dic];
     */
    
    //photo
    if ( user.profileImageUrl_s && [user.profileImageUrl_s length]>0 ) {
        UIImage* image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:user.profileImageUrl_s]]];
        contact.image = image;
    }
    else {
        UIImage* image = [ImageStore defaultProfileImage:NO];
        contact.image = image;
    }
    
    ABNewPersonViewController *npvc = [[ABNewPersonViewController alloc] init];
    npvc.newPersonViewDelegate = self;
    npvc.displayedPerson = contact.record;
    npvc.title = @"新联系人";
    //[self presentModalViewController:npvc animated:YES];
    [self.navigationController pushViewController:npvc animated:YES];
    [npvc release];
}


- (void) createFriendship
{
    //关注
    [UserService createFriendship:user];
    [[[GuaziAppDelegate getAppDelegate] friendsViewController] refreshCreateFriendship:user];
}


- (void) destroyFriendship
{
    //取消关注
    [UserService destroyFriendship:user];
    [[[GuaziAppDelegate getAppDelegate] friendsViewController] refreshDestroyFriendship:user.userId];
}


- (void) actionSheet:(UIActionSheet*)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if ( actionSheet.tag == kActionSheetBind ) {
        //添加到通讯录
        if ( buttonIndex == 0 ) {
            [self didBindToAContact];
        }
        else if ( buttonIndex == 1 ) {
            [self didBindToNewContact];
        }
    }
    else if ( actionSheet.tag == kActionSheetFollow ) {
        if ( buttonIndex == 0 ) {
            [self destroyFriendship];
            NSIndexPath* indexPath = [NSIndexPath indexPathForRow:0 inSection:2];
            ButtonCell* cell = (ButtonCell*) [self.tableView cellForRowAtIndexPath:indexPath];
            if ( cell ) {
                [self showFollowButton:cell];
            }
        }
    }
    else if ( actionSheet.tag == kActionSheetRequestCard ) {
        if ( buttonIndex == 0 ) {
            [self askCard];
        }
    }
}


- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
	ABContact* abContact = [ABContact contactWithRecord:person];
	[self updateUserWithABContact:abContact];
	[self dismissModalViewControllerAnimated:YES];
	[peoplePicker release];
	return NO;
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier
{
	// required method that is never called in the people-only-picking
	[self dismissModalViewControllerAnimated:YES];
	[peoplePicker release];
	return NO;
}

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
	[self dismissModalViewControllerAnimated:YES];
	[peoplePicker release];
}


- (void) updateUserWithABContact:(ABContact*)abContact
{
	user.contact = YES;
	user.contactName = [abContact compositeName];
	NSArray* arr = abContact.phoneArray;
	if ( arr != nil && [arr count] > 0 ) {
		user.phone = [abContact.phoneArray objectAtIndex:0];
	}
	[user updateDB:YES withName:YES withAccount:NO];
}


- (void) friendship:(ButtonCell*)cell
{
    if ( ownInfo ) return;
    
    if ( [user.relation compare:kUserRelationFollowing]==NSOrderedSame || [user.relation compare:kUserRelationBoth]==NSOrderedSame) {
        NSString* message = nil;
        if ( [user.relation compare:kUserRelationBoth]==NSOrderedSame || [user.relation compare:kUserRelationFollowing]==NSOrderedSame ) {
            message = [NSString stringWithFormat:@"您已经关注了%@。是否确认取消关注?", user.remarkName];
        }
        else if ( [user.relation compare:kUserRelationSilence]==NSOrderedSame ) {
            message = [NSString stringWithFormat:@"您已经默默关注了%@。是否确认取消默默关注?", user.remarkName];
        }
        else {
            return;
        }
        UIActionSheet* as = [[UIActionSheet alloc] initWithTitle:message 
                                                        delegate:self 
                                               cancelButtonTitle:@"取消" 
                                          destructiveButtonTitle:@"确定" 
                                               otherButtonTitles:nil];
        as.tag = kActionSheetFollow;
        [as showInView:[GuaziAppDelegate getAppDelegate].tabBarController.view];
        [as release];
    }
    else {
        [self createFriendship];
        [self showFollowButton:cell];
    }
}



#pragma mark - NEW PERSON DELEGATE METHODS
- (void)newPersonViewController:(ABNewPersonViewController *)newPersonViewController didCompleteWithNewPerson:(ABRecordRef)person
{
	if (person)
	{
		ABContact *contact = [ABContact contactWithRecord:person];
		if (![ABContactsHelper addContact:contact withError:nil])
		{
			// may already exist so remove and add again to replace existing with new
			[contact removeSelfFromAddressBook:nil];
			[ABContactsHelper addContact:contact withError:nil];
		}
		
		[self updateUserWithABContact:contact];
	}
	
	[self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - SMS operations

-(void) send:(NSArray*)recipients body:(NSString*)body
{
	Class messageClass = (NSClassFromString(@"MFMessageComposeViewController"));
	if (messageClass != nil) {
		// Check whether the current device is configured for sending SMS messages
		if ([messageClass canSendText]) {
			[self displaySMSComposerSheet:recipients body:body];
		}
		else {
			UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"设备没有短信功能" 
															message:@"您的设备不能发送短信" 
														   delegate:nil 
												  cancelButtonTitle:@"确定" 
												  otherButtonTitles:nil];
			[alert show];
			[alert release];
		}
	}
	else {
		UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"iOS版本过低" 
														message:@"iOS版本过低,iOS4.0以上才支持程序内发送短信" 
													   delegate:nil 
											  cancelButtonTitle:@"确定" 
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
	}
}


-(void)displaySMSComposerSheet:(NSArray*)recipients body:(NSString*)body
{
	MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
	picker.messageComposeDelegate = self;
	picker.recipients = recipients;
	picker.body = body;
    picker.title = @"发送短信";
    
	[self.navigationController presentModalViewController:picker animated:YES];
	[picker release];
}


- (void)messageComposeViewController:(MFMessageComposeViewController *)messageComposeViewController
				 didFinishWithResult:(MessageComposeResult)result {
	switch (result)
	{
		case MessageComposeResultCancelled:
			NSLog(@"Result: SMS sending canceled");
			break;
		case MessageComposeResultSent:
			NSLog(@"Result: SMS sent");
			break;
		case MessageComposeResultFailed:
			NSLog(@"Result: sms fail");
			UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"短信发送失败" 
															message:@"短信发送失败" 
														   delegate:nil 
												  cancelButtonTitle:@"确定" 
												  otherButtonTitles:nil];
			[alert show];
			[alert release];
			break;
		default:
			NSLog(@"Result: SMS not sent");
			break;
	}
    
    [self.navigationController dismissModalViewControllerAnimated:YES];
}


@end
